<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="global.Constants"%>
<%@page import="com.aiflow.Action.DictionaryAction;"%>
<html>
<head>
	<%
		String baseUrl = request.getContextPath();
	%>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<script type="text/javascript">
	    //这里的全局是为了修改之后的刷新
	    var heraldListGrid;
		$(document).ready(function(){
		    //角色勾选的变量
		    var checkid;
		    var checktext;
		    //部门的变量
		    var deptid;
		    var depttext;
			// 全局参数
			var baseParams = {limit:<%=Constants.PAGE_SIZE %>,start : 0};
			var EXT_QUERY_TIME_OUT = 1200000;
     
            var isSendButton ;
			// 传报数据源
		    var heraldListStore = new Ext.data.JsonStore({
		        url: '${pageContext.request.contextPath}/herald_findAlarms.action',
		        root: 'datas',
				timeout : EXT_QUERY_TIME_OUT,
		        totalProperty: 'results',
		        fields: ['id','alarm_name','alarm_id','alarm_target','target_name','pattern','staTime','endTime','pulse'],
		        baseParams: baseParams,
		        autoLoad: true,
				listeners : {  
          load : function(r) {  
              isDetailReady = true;// 查询置换标志为已查过
              var count = this.getCount();
              if(count >0){
               var ob =  this.getRange(0,1);
               var arr = ob[0];
                var pulse = arr.get('pulse');
               if(pulse == '关闭'){
                isSendButton = 0;
                Ext.getCmp('noSend-button').disable(); 
                Ext.getCmp('send-button').enable();
               }else if(pulse =='开启'){
               isSendButton = 1; 
                Ext.getCmp('send-button').disable();
                Ext.getCmp('noSend-button').enable();
               }
                // alert(ob.get("id"));
              }
            }  
            }  
		    });
		    
		   	// 工具栏
		    var heraldListToolbar = new Ext.Toolbar({
		    	renderTo: 'heraldListToolBarDiv',
		    	items: [
					new Ext.Button({
					    id: 'heraldList-add-button',
					    text: '添加',
						iconCls: 'phone_add'
						//disabled:true
					}),
					new Ext.Button({
					    id: 'heraldList-update-button',
					    text: '编辑传报',
						iconCls: 'phone'
					}),
					new Ext.Button({
					    id: 'heraldList-delete-button',
					    text: '删除',
						iconCls: 'phone_delete'
					}),
					'-',
		            new Ext.Button({
					    id: 'send-button',
					    text: '启动',
						iconCls: 'control_play'
					}),
					new Ext.Button({
					    id: 'noSend-button',
					    text: '关闭',
						iconCls: 'control_stop_blue'
					}),
		            new Ext.ux.form.SearchField({
		                store: heraldListStore,
		                width: 320,
		                paramName: 'name',
		                emptyText: '请输入告警类型',
		                style: 'margin-left: 10px;'
		            })
				]
			});

			// 数据表格
			var sm = new Ext.grid.CheckboxSelectionModel();
			heraldListGrid = new Ext.grid.GridPanel({
				id: 'heraldListGrid',
				renderTo: 'heraldListGridDiv',
				border: false,
				stateful: true,
			    autoScroll: 'auto',
		        store: heraldListStore,
		        loadMask: true,
		        cm: new Ext.grid.ColumnModel({
		            defaults: {
		                width: 100,
		                sortable: true
		            },
			        columns: [
						sm,
						new Ext.grid.RowNumberer({header:'№',width:50}),
						{id:'id',header: '传报编号', width: 200, hidden: true, sortable: true, dataIndex: 'id'},
						{id:'alarm_name',header: '告警类型', width: 150, hidden: false, sortable: true, dataIndex: 'alarm_name'},
			            {id:'alarm_id',header: '告警类型id', width: 100,hidden: true, sortable: true, dataIndex: 'alarm_id'},
			            {id:'alarm_target',header: '告警级别编号', width: 200,hidden: true, sortable: true, dataIndex: 'alarm_target'},
			            {id:'target_name',header: '传报对象', width: 200, sortable: true, dataIndex: 'target_name'},		
			             {id:'pattern',header: '传报格式', width: 200, sortable: true, dataIndex: 'pattern'},	
			             {id:'staTime',header: '发送开始时间', width: 100, sortable: true, dataIndex: 'staTime'},	
			             {id:'endTime',header: '发送结束时间', width: 100, sortable: true, dataIndex: 'endTime'},
			             {id:'pulse',header: '是否启动', width: 100, sortable: true, dataIndex: 'pulse'}		
			             	         					]
		        }),
		        sm: sm,
		        columnLines: true,
		        bbar: new Ext.PagingToolbar({
					pageSize: <%=Constants.PAGE_SIZE %>,
					store: heraldListStore,
					displayInfo: true,
					displayMsg: Anynote.PAGINGTOOLBAR_DISPLAYMSG,
					emptyMsg: Anynote.PAGINGTOOLBAR_EMPTYMSG,
					doLoad: function(start){
						baseParams.start = start;
						this.store.load({params: baseParams});
					}
		        })
		    });
			// 设置Grid高度和宽度
			Anynote.resizeGridTo("heraldListGrid", 0, 56);
			
			// 添加按钮
			$("#heraldList-add-button").click(function(){ //////////////////////
			  
		    // 告警类型数据源
	        var alarmStoreAdd = new Ext.data.ArrayStore({  
	            fields : ['alarm_id', 'alarm_name'],  
	            data : <%=DictionaryAction.getDictionaryCombo("79")%>,
	            sortInfo: {field: "alarm_id", direction: "ASC"}
	        });

		   //  告警对象 树      
		   var comboWithTooltipHeraldAdd = new Ext.form.ComboBox({
		    fieldLabel: '传报对象',
            store:new Ext.data.SimpleStore({fields:[],data:[[]]}),  
            editable:false,  
            hiddenName:'targetName',
           //  hiddenId:'dicId',
             hiddenId:'alarmTargetId',
            mode: 'local',  
            triggerAction:'all',  
			allowBlank:false,
            maxHeight: 200,  
            tpl: '<div style="height:200px"><div id="treeHeraldAdd"></div></div>',  
            onSelect:Ext.emptyFn,
            emptyText:'请选择...',
            anchor:'98%',
            //applyTo: 'comboxtreeHeraldAdd'  
            renderTo : Ext.getBody()
        });
         
        comboWithTooltipHeraldAdd.render('comboWithTooltipHeraldAdd');  
           
        var treeHeraldAdd = new Ext.tree.TreePanel({  
                border:false,  
                autoScroll:true,
                animate:true,
                autoWidth:true,
                autoHeight:true,
                enableDD:true,
                containerScroll: true, 
                loader: new Ext.tree.TreeLoader({
                    dataUrl:'${pageContext.request.contextPath}/dictionary_getDictionaryTreeNew.action',
                    listeners : {
					beforeload : function(treeLoader, node) {
						this.baseParams.parentId = node.id
						this.baseParams.text = node.text
						this.baseParams.leaf = node.leaf
					}
				}           
                })
            });
            
        var rootHerald = new Ext.tree.AsyncTreeNode({
                id:'76',                      //节点id
                text: '传报对象',                  //节点名称
                draggable:true,                  //是否支持拖动
                nodeType: 'async', 
                leaf:false,
                checked : false
        });
          
            treeHeraldAdd.setRootNode(rootHerald);
            comboWithTooltipHeraldAdd.on('expand',function(){  
            treeHeraldAdd.render('treeHeraldAdd');  
            //加载所有的子节点
            //tree.expandAll(); 
            });  
            
        treeHeraldAdd.on('checkchange', function(node, checked) {
                        node.expand();
                        node.attributes.checked = checked;
                        node.eachChild(function(child) {
                                    child.ui.toggleCheck(checked);
                                    child.attributes.checked = checked;
                                    child.fireEvent('checkchange', child,
                                            checked);
                               });
                            //这里是遍历勾选的角色
                            var b = treeHeraldAdd.getChecked();
                            checkid = new Array;// 存放选中id的数组
                            checktext = new Array;// 存放选中text的数组
                            for (var i = 0; i < b.length; i++) {
                                checktext.push(b[i].text);// 添加text到数组
                                checkid.push(b[i].id);// 添加id到数组
                                
                            }
                       comboWithTooltipHeraldAdd.setValue(checktext.toString());
                    }, treeHeraldAdd);
            
				// 新增传报Form
				var addUserFormPanel = new Ext.FormPanel({
					id: 'addUserFormPanel',
			        labelWidth: 60,
			        buttonAlign: 'center',
			        border: false,
			        bodyStyle: 'padding:10px;text-align:left;background-color:transparent;',
			        url: '',
		            items:[{// 账号
			                xtype:'textfield',
			                id: 'pulse',
			                name: 'pulse',
			                fieldLabel: 'ss',
			                anchor:'98%',
			                allowBlank:false,
			                maxLength: 20,
			                value:isSendButton,
			                hidden: true
			           },{  
			                xtype:'combo',
			                hiddenName: 'alarm_id',
			      
			                fieldLabel: '告警类型',
			                store: alarmStoreAdd,
			                mode : 'local',
			                triggerAction: "all",
			                valueField: 'alarm_id',
			                displayField: 'alarm_name',
			                allowBlank:false,
			                editable: false,
			                width: 230,
			                anchor:'98%'
			           },
		                  comboWithTooltipHeraldAdd,
		               { 
		xtype:'timefield',  
		columnWidth:.5 ,            
                maxValue:'23:30',                      //最大时间   
                maxText:'所选时间小于{0}',  
                minValue:'00:00',                      //最小时间   
                minText:'所选时间大于{0}',  
                maxHeight:70,  
                increment:30,   
                name: 'startTime', 
                id: 'heraldstartTime', 
				allowBlank:false, 
		anchor:'68%' ,                   //时间间隔   
                format:'G:i:s',                    //时间格式   
                invalidText:'时间格式无效',  
                fieldLabel:'开始时间'  
				},{ 
						xtype:'timefield',  
		columnWidth:.5 ,            
                maxValue:'23:30',                      //最大时间   
                maxText:'所选时间小于{0}',  
                minValue:'00:00',                      //最小时间   
                minText:'所选时间大于{0}',  
                maxHeight:70,  
                increment:30,   
				allowBlank:false,
                name: 'endTime', 
                id: 'heraldendTime',  
		anchor:'68%' ,                   //时间间隔   
                format:'G:i:s',                    //时间格式   
                invalidText:'时间格式无效',  
                fieldLabel:'结束时间'
				},{//   格式
			                xtype:'textarea',
			                name: 'pattern',
			                fieldLabel:'传报格式',
			                width: 230,
			                anchor:'98%',
							allowBlank:false
			              
		                }],
			        buttons: [{
	                    text:'提交',
	                    handler: function(){
				        	var form = addUserFormPanel.getForm();
				        	alert(form.isValid());
						    if(form.isValid()){
						     //    form.findField('rolename').setValue(checktext.toString());
						    	// 发送请求
								Anynote.ajaxRequest({
									baseUrl: '<%=baseUrl %>',
									baseParams: form.getValues(),
									action: '${pageContext.request.contextPath}/herald_addHerald.action?checkid='+checkid.toString(),
									callback: function(jsonResult){
										heraldListGrid.getStore().reload();
										addUserWindow.close();
									},
									showWaiting: true,
									failureMsg: '保存失败.'
								});
							}
	                	}
	                },{
	                    text: '重置',
	                    handler: function(){
	                		addUserFormPanel.getForm().reset();
	                    }
	                }]
			    });
				// 传报注册窗口
				var addUserWindow = new Ext.Window({
					title: '添加传报',
					width: 330,
					height: 290,
					modal: true,
					maximizable: false,
					resizable: false,
					iconCls: 'phone_add',
					layout:'fit',
					plain: true,
					items: [addUserFormPanel]
				}).show();
			});

			// 启用编辑 
			$("#heraldList-update-button").click(function(){
				// 启用
				submit("update");
			});

			// 删除按钮
			$("#heraldList-delete-button").click(function(){
				// 提交
				submit("delete");
			});
			
		    // 修改告警类型 按钮
			$("#send-button").click(function(){
				// 提交
			     Ext.getCmp('send-button').disable();
				isSend("1");
			});
			
			 $("#noSend-button").click(function(){
				// 提交
				// this.disable();
			 	Ext.getCmp('noSend-button').disable();
				isSend("0");
			});

			// 提交
			function submit(type){
				var msg = "";
				var status = 0;
				if(type=="delete"){
				    status = 1;
					msg = "确定要删除该传报吗？";
				}else if(type=="update"){
				    status = 2;
				}else if(type=="updateType"){
				    status = 3;
				}
				var records = heraldListGrid.getSelectionModel().getSelections();
				
				if(records.length < 1){
					 Ext.Msg.alert("提示", "请至少选择一条数据.");
				}else{
					   //如果点击的是删除传报
					   if(status == 1 ){
					      Ext.Msg.confirm("警告", msg, function(btn){
						  if(btn=="yes"){
							var heraldIds = "";
							for(var i=0;i<records.length;i++){
								heraldIds = heraldIds + records[i].get("id") + ",";
							}
							// 发送请求
							Anynote.ajaxRequest({
								baseUrl: '<%=baseUrl %>',
							    baseParams: {heraldIds:heraldIds },
								action: '${pageContext.request.contextPath}/herald_deleteHeral.action',
								callback: function(jsonResult){
									heraldListGrid.getStore().reload();
								},
								showWaiting: true,
								failureMsg: '保存失败.'
							});
						   }
					     });
					   } //如果点击的是编辑传报
					   else if(status == 2){
					        var heraldIds = "";
						    heraldIds = records[0].get("id");
					        //只能一条一条的编辑，不能多个一起编辑
					        if(records.length == 1){
						        editHeraldWindow = new Ext.Window({
								title: '编辑传报',
								width: 330,
								height: 290,
								modal: true,
								maximizable: false,
								resizable: false,
								iconCls: 'phone',
								layout:'fit',
								plain: true,
								autoLoad:{url:'${pageContext.request.contextPath}/page/bussmodule/heraldManager/editHerald.jsp?heraldIds='+heraldIds,scripts:true,nocache:true},
								listeners: {
									close: function(){
                                       if(Ext.getCmp('ch') != null){Ext.getCmp('ch').destroy()};//把它destroy就可以了}
									}
								}
								});
								editHeraldWindow.show();
					        }else{
					            Ext.Msg.alert("提示", "只能选择一条数据.");
					        }
					   }
					}
			}
			
			
			function isSend(finringType){
		     //	var records = heraldListGrid.getSelectionModel().getSelections();
		     //	if(records.length < 1){
			//		 Ext.Msg.alert("提示", "请至少选择一条数据.");
			//	}else{
		             //	var heraldIds = "";
					//		for(var i=0;i<records.length;i++){
					//			heraldIds = heraldIds + records[i].get("id") + ",";
					//		}
							// 发送请求							
							Anynote.ajaxRequest({
								baseUrl: '<%=baseUrl %>',
							       baseParams: {finring:finringType},
								action: '${pageContext.request.contextPath}/herald_updateFinring.action',
								callback: function(jsonResult){
									heraldListGrid.getStore().reload();
								},
								showWaiting: true,
								failureMsg: '保存失败.'
							});
				//	 }
		       }
});

	</script>
</head>
<body>
<div id="heraldListDiv">
	<div id="heraldListToolBarDiv"></div>
	<div id="heraldListGridDiv" style="width:100%;height:100%;"></div>
</div>

</body>
</html>
